const mongoose = require('mongoose')
const Schema = mongoose.Schema
const ObjectId = Schema.Types.ObjectId
const Dialog = mongoose.model('Dialog')

const MessageSchema = new Schema({
  // 消息类型
  messageType: {
    type: String,
    default: 'text'
  },
  content: {
    type: String,
    default: ''
  },
  meta: {
    createdAt: {
      type: Date,
      default: Date.now()
    },
    updatedAt: {
      type: Date,
      default: Date.now()
    }
  },
  read: [{
    type: ObjectId,
    ref: 'User'
  }],
  belongsTo: {
    type: ObjectId,
    ref: 'User'
  },
  dialog: {
    type: ObjectId,
    ref: 'Dialog'
  }
})

MessageSchema.pre('save', async function(next) {
  if (this.isNew) {
    this.meta.createdAt = this.meta.updatedAt = Date.now()
  } else {
    this.meta.updatedAt = Date.now()
  }

  next()
})

mongoose.model('Message', MessageSchema)